const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
const WxSearch = require('./indexSearch.js');

//获取应用实例
const app = getApp()
Page({
  data: {
    banner: [],
    project: [],
    recommendTeacher: [],
    ad: false,
    current_city: '',
    imgalist: ['https://knowif.oss-cn-beijing.aliyuncs.com/tutorPicture/%E5%B0%8F%E7%A8%8B%E5%BA%8Fbanner/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20190629223810.png'],
    currentTab: 0, //首页顶部切换
    tabTrue: '../../images/index/offsericon-3-on.png',
    tabFalse: '../../images/index/offericon-3.png',
    checked:true,
    checkboxChecked: false,
    degree: [
      { value: '1', name: '基本信息', checked: '' },
      { value: '2', name: '标化成绩', },
      { value: '3', name: '留言', },
    ],
    offer:[],
    offerSub: "",
    interviewExperiences:[],
    radioIsChecked:false,
    // userId:''
  },
  isHideNameChange: function (e) {
    let isHideName = this.data.checkboxChecked;
    isHideName = !isHideName;
    console.log(isHideName)
    this.setData({
      checkboxChecked: isHideName,
      isAnonymous: isHideName ? 1 : 0
    })
  },
  getIndexData: function() {
    let that = this;
    console.log("初始化")
    util.request(api.OfferIndex).then(function(res) {
      if (res.code === 200) {
        let offer = res.result.offers;
        let interviewExperiences = res.result.interviewExperiences;
        that.setData({
          offer,
          interviewExperiences
        })
        console.log(that.data.interviewExperiences)
      }
    });
  },
  goToSearch: function() {
    wx.navigateTo({
      url: '../../myPages/search/search'
    })
  },
  // 基本信息跳到发布offer
  goToSendOffer:function(){
    var offer = this.data.offerSub;
    if(!offer || offer === ""){
      wx.navigateTo({
        url: '../../pages/sendOffer/sendOffer'
      })
    }else{
      wx.navigateTo({
        url: '../../pages/sendOffer/sendOffer?offer='+JSON.stringify(offer)
      })
    }

  },
  // 标化成绩
  goToScores: function () {
    var standerSorce = this.data.standerSorce;
    var transform = "";
    if(standerSorce){
      transform = JSON.stringify(standerSorce);
    }
    wx.navigateTo({
      url: '../../pages/scores/scores?standerSorce='+transform
    })
  },
  // 留言
  goToMsg: function () {
    console.log(this.data);
    var standerMsg = this.data.standerMsg;
    var transform = "";
    if(standerMsg){
      transform = JSON.stringify(standerMsg);
    }
    wx.navigateTo({
      url: '../../pages/writeMsg/writeMsg?standerMsg='+transform
    })
  },
  goToTeacher: function(e) {
    if (e.currentTarget.dataset.id != undefined) {
      wx.navigateTo({
        url: '../../myPages/teacher/teacher?teacherId=' + e.currentTarget.dataset.id
      })
    }
  },
  goToTeacherDetail: function(e) {
    wx.navigateTo({
      url: '../../myPages/teacherDetail/teacherDetail?teacherId=' + e.currentTarget.dataset.id
    })
  },
  goToOffer: function(e) {
    let offerId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../../pages/offerDetails/offerDetails?offerId=' + offerId
    })
  },
  goToInterview: function (e) {
    let interviewId = e.currentTarget.dataset.id
    console.log(interviewId)
    wx.navigateTo({
      url: '../../pages/expDetails/expDetails?offerInterviewId=' + interviewId
    })
  },
  goToProcess: function(e) {
    wx.navigateTo({
      url: '../../myPages/process/process'
    })
  },
  // 跳转面经填写
  goToWriteEXP: function () {
    wx.navigateTo({
      url: '../../pages/writeEXP/writeEXP'
    })
  },
  // //图片预览
  // previewImage: function(e) {
  //   console.log(e.currentTarget.dataset.linkurl)
  //   if (e.currentTarget.dataset.linkurl != '') {
  //     var url = [e.currentTarget.dataset.linkurl];
  //     wx.previewImage({
  //       current: url, // 当前显示图片的http链接   
  //       urls: url // 需要预览的图片http链接列表   
  //     })
  //     wx.getImageInfo({ // 获取图片信息
  //       src: url[0],
  //       success: function(res) {}
  //     })
  //   }
  // },
  // close() {
  //   this.setData({
  //     ad: false
  //   })
  // },
  degreeTypeRadioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    const degree = this.data.degree;
    for (let i = 0, len = degree.length; i < len; ++i) {
      degree[i].checked = degree[i].value === e.detail.value
    }
    this.setData({
      degree: degree,
      offerType: e.detail.value
    })
  },
  // 首页顶部tab切换
  swichNav: function(e) {
    var that = this;
    console.log(that)
    // console.log(e.currentTarget.dataset.current)
    if (e.currentTarget.dataset.current == '2'){
      that.setData({
        tabFalse: '../../images/index/offsericon-3-on.png',
      })
      wx.hideTabBar()
    }else{
      that.setData({
        tabFalse: '../../images/index/offericon-3.png',
      })
      wx.showTabBar()
    }
    if (this.data.currentTab === e.currentTarget.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.currentTarget.dataset.current
      })
    }
    if (e.currentTarget.dataset.current == 2){
      let standerSorce = wx.getStorageSync('standerSorce');
      console.log('standerSorce', standerSorce)
    }
  },
  bindChange: function(e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },
  isHideNameChange: function (e) {
    let isHideName = this.data.checkboxChecked;
    isHideName = !isHideName;
    console.log(isHideName)
    this.setData({
      checkboxChecked: isHideName,
      isAnonymous: isHideName ? 1 : 0
    })
  },
  // 搜索栏
  onLoad: function () {
    var that = this;
    WxSearch.init(
      that, // 本页面一个引用
      ["考研", "金融硕士", "高考志愿", "美国留学", "雅思考试"], // 热点搜索推荐，[]表示不使用
      ["考研", "金融硕士", "高考志愿", "美国留学", "雅思考试"], // 搜索匹配，[]表示不使用
      that.mySearchFunction, // 提供一个搜索回调函数
      that.myGobackFunction //提供一个返回回调函数
    );
  },
  onReady: function() {
    // 页面渲染完成
    this.getIndexData();
  },
  onShow: function() {
    var successSubmit = wx.getStorageSync('successSubmit');
    console.log(successSubmit)
    if(successSubmit){
      wx.removeStorageSync("successSubmit");
      this.setData({
        currentTab:0
      })
      wx.showToast({
        title: '恭喜您！提交成功啦！现在您可以去【个人中心】-【创作中心】查看您的发布！',
        icon: 'none',
        duration: 2200
      })
    }
    var userId = wx.getStorageSync('userInfo').id //获取用户id
    if (userId == null || userId == undefined) {
      wx.navigateTo({
        url: "../../myPages/authorize/authorize"
      })
    }
    console.log('onShow is invoked');
    var standerSorce = wx.getStorageSync('standerSorce');
    var standerMsg = wx.getStorageSync('standerMsg');
    var offer = wx.getStorageSync('offer');
    console.log(offer);
    if(standerSorce && "" != standerSorce){
      this.setData({
        standerSorce : standerSorce
      })
      wx.removeStorageSync('standerSorce');
    }
    if(standerMsg && "" != standerMsg){
      this.setData({
        standerMsg : standerMsg
      })
      wx.removeStorageSync('standerMsg');
    }
    if(offer && "" != offer){
      this.setData({
        offerSub : offer
      })
      wx.removeStorageSync('offer');
    }
    var flag = wx.getStorageSync('sendOfferSuccess');
    console.log(flag);
    if(flag){
      this.setData({
        currentTab : 0
      });
      wx.removeStorageSync('sendOfferSuccess');
    }

    console.log(this.data);
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  /*下拉刷新*/
  onPullDownRefresh: function() {
    this.getIndexData();
    wx.stopPullDownRefresh();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let that = this;
    return {
      title: '知识鸭', // 转发后 所显示的title
      path: '/pages/index/index', // 相对的路径
      imageUrl: "https://knowif.oss-cn-beijing.aliyuncs.com/994228D65EDA40E296EC95FBC37E1732.PNG",
      success: (res) => { // 成功后要做的事情
        wx.getShareInfo({
          shareTicket: res.shareTickets[0],
          success: (res) => {},
          fail: function(res) {
            console.log(res)
          },
          complete: function(res) {
            console.log(res)
          }
        })
      },
      fail: function(res) {
        // 分享失败
        console.log(res)
      }
    }
  },
  resetStander: function(){
    
  },
  // standerScore提交
  standerScoreSubmit:function(){
    
    var that = this;
    var offer = that.data.offerSub;
    console.log(offer);
    var flag = false;
    if(offer == null || "" == offer){
      //这里需要提示，必须要填基本信息
      wx.showToast({
        title: '请填写基本信息后提交',
        icon: 'none',
        duration: 1500
      })
      return;
    }else{
      flag = true;
    }
    var standerSorce = that.data.standerSorce;
    if(standerSorce && standerSorce !== null){
      var standerMsg = that.data.standerMsg;
      console.log(standerSorce)
      if(standerMsg && standerMsg != null){
        standerSorce.otherInstructions = standerMsg.otherInstructions;
        standerSorce.leaveMessage = standerMsg.leaveMessage;
      }
      var scoresStr = JSON.stringify(standerSorce.scores);
      scoresStr = "[" + scoresStr +"]";
      standerSorce.scores = scoresStr;
      //将score转为字符串
      console.log(standerSorce.scores)
    }else{
      standerSorce = {};
    }
    var userId = wx.getStorageSync('userInfo').id;
    standerSorce.userId = userId;
    var offerDto = {
      offer : offer,
      standerSorce : standerSorce
    }
    console.log(offerDto)
    util.request(api.OfferAndStandersorce, offerDto, "POST", true).then(function(res){
      console.log(res)
      if(res.code === 200){
        wx.showToast({
          title: '恭喜您！提交成功啦！现在您可以去【个人中心】-【创作中心】查看您的发布！',
          icon: 'none',
          duration: 2200
        })
        that.setData({
          standerSorce : null,
          standerMsg : null,
          offerSub : null
        });
        that.setData({
          currentTab : 0
        })
        console.log("发布成功")
      }else{
        //发布不成功！
        wx.showToast({
          title: '发布失败',
          icon: 'none',
          duration: 1500
        })
      }
    });

    // else{
    //   //这里需要提示，必须要填标准化成绩
    //   wx.showToast({
    //     title: '请填写标化成绩',
    //     icon: 'none',
    //     duration: 1500
    //   })
    // }
  },
  // 转发函数,固定部分
  wxSearchInput: WxSearch.wxSearchInput, // 输入变化时的操作
  wxSearchKeyTap: WxSearch.wxSearchKeyTap, // 点击提示或者关键字、历史记录时的操作
  wxSearchDeleteAll: WxSearch.wxSearchDeleteAll, // 删除所有的历史记录
  wxSearchConfirm: WxSearch.wxSearchConfirm, // 搜索函数
  wxSearchClear: WxSearch.wxSearchClear, // 清空函数

  // 搜索回调函数  
  mySearchFunction: function (value) {
    console.log(value)
    // do your job here
    let searchCondition = {
      pageSize: 20,
      pageNum: 1,
      conditionList: [],
      sort: {}
    };
    let condition = {
      operator: 7,
      code: 'searchContent',
      value: value,
      type: 'String'
    }
    searchCondition.conditionList.push(condition)
    console.log(searchCondition)

    let that = this;
    util.request(api.SearchUrl, searchCondition, 'POST', true).then(function (res) {
      if (res.code === 200) {
        console.log(res)
        //设置介绍文字
        res.result.forEach((value, index, arr) => {
          let userEducationExperiencesTXT = "";
          for (let i in value.userEducationExperiences) {
            if (i == value.userEducationExperiences.length - 1) {
              userEducationExperiencesTXT += value.userEducationExperiences[i].college
            } else {
              userEducationExperiencesTXT += value.userEducationExperiences[i].college + " | "
            }
          }
          value.userEducationExperiencesTXT = userEducationExperiencesTXT.substring(0, userEducationExperiencesTXT.length)
          userEducationExperiencesTXT = "";
        })
        that.setData({
          userinfo: res.result
        });
      } else {
        wx.showModal({
          title: '提示',
          content: res.message,
          showCancel: false
        })
      }
    });
  },
  // 返回回调函数
  myGobackFunction: function () {
    // do your job here
    // 跳转
    /* wx.redirectTo({
       url: '../index/index?searchValue=返回'  
     })
     */
    wx.navigateBack()
  },
})